//
//  QYEvaluationViewController.m
//  YSFDemo
//
//  Created by liaosipei on 2019/6/11.
//  Copyright © 2019 Netease. All rights reserved.
//

#import "QYEvaluationViewController.h"
#import "QYEvaluationResolveView.h"


static CGFloat kEvaluationContentPortraitHeight = 377;
static CGFloat kEvaluationContentLandscapeHeight = 220;
static CGFloat kEvaluationButtonTitleInset_Top = 70;
static CGFloat kEvaluationButtonTitleInset_Left = -40;
static CGFloat kEvaluationTitleHeight = 40;
static CGFloat kEvaluationCloseSize = 40;
static CGFloat kEvaluationSatisButtonTop = 20;
static CGFloat kEvaluationSatisButtonWidth = 60;
static CGFloat kEvaluationTagViewMargin = 16;
static CGFloat kEvaluationTagViewTop = 90;
static CGFloat kEvaluationTagButtonMargin = 10;
static CGFloat kEvaluationTagButtonGap = 10;
static CGFloat kEvaluationSubmiteHeight = 70;
static CGFloat kEvaluationSubmiteButtonHeight = 42;

static CGFloat kEvaluationTextViewHeight = 62;
static CGFloat kEvaluationTextViewDefaultTop = 110;


typedef NS_ENUM(NSInteger, QYEvaluationSubmitType) {
    QYEvaluationSubmitTypeEnable = 0,  //提交，可点击
    QYEvaluationSubmitTypeUnable,      //提交，不可点击
    QYEvaluationSubmitTypeSubmitting,  //提交中，不可点击
};


@interface QYEvaluationViewController () <UIAlertViewDelegate, UITextViewDelegate, QYEvaluationResolveViewDelegate>

@property (nonatomic, weak) QYSessionViewController *sessionViewController;
//@property (nonatomic, copy) evaluationCallback evaluationCallback;  //结果回调

@property (nonatomic, strong) UIView *contentView;          //内容区域
@property (nonatomic, strong) UIView *topLineView1;         //分割线
@property (nonatomic, strong) UILabel *titleLabel;          //标题
@property (nonatomic, strong) UIButton *closeButton;        //关闭按钮
@property (nonatomic, strong) UIView *topLineView2;         //分割线
@property (nonatomic, strong) UIScrollView *scrollView;     //滚动区域
@property (nonatomic, strong) NSMutableArray *satisButtons; //满意度按钮集合
@property (nonatomic, strong) NSMutableArray *tagViews;     //标签视图集合
@property (nonatomic, strong) UITextView *textView;         //备注输入区域
@property (nonatomic, strong) UILabel *placeholderLabel;    //备注默认
@property (nonatomic, strong) UIView *bottomLineView;       //分割线
@property (nonatomic, strong) UIButton *submitButton;       //提交按钮
@property (nonatomic, strong) QYEvaluationResolveView *resolveView;  //问题解决

@property (nonatomic, strong) UIButton *selectedButton;      //选中按钮
@property (nonatomic, strong) UIView *selectedTagView;       //选中标签视图

@property (nonatomic, assign) CGRect kbFrame;

@end


@implementation QYEvaluationViewController
- (void)dealloc {
    
}

- (instancetype)init {
    self = [super init];
    if (self) {

        _kbFrame = CGRectZero;
        
        _satisButtons = [NSMutableArray array];
        _tagViews = [NSMutableArray array];
    UIButton * textShowButtonTo1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
        NSString * textShowButtonTitleTo1 = @"测试功能";
        [textShowButtonTo1 setTitle:textShowButtonTitleTo1 forState:UIControlStateNormal];
        NSInteger textShowArcTo1 = arc4random_uniform(22);
        NSLog(@"随机数：%ld", (long)textShowArcTo1);
    }
    return self;
}

-(void)showTextViewNavViewTo1{
    NSMutableArray * showTextViewNavViewNameArrTo1 = [NSMutableArray new];
    UIView * showTextViewNavViewViewTo1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    showTextViewNavViewViewTo1.clipsToBounds = YES;
       UILabel * oldshowSSSSTip = [[UILabel alloc]init];
    oldshowSSSSTip.clipsToBounds = YES;
    oldshowSSSSTip.text = @"kass显示区";
    oldshowSSSSTip.textColor = ColorHex(@"#f0f0f0");
    oldshowSSSSTip.textAlignment = NSTextAlignmentCenter;
    oldshowSSSSTip.font = [UIFont systemFontOfSize:28];
    oldshowSSSSTip.hidden = YES;
    [self.view addSubview:oldshowSSSSTip];
    [self.view addSubview:showTextViewNavViewViewTo1];
    UILabel * showTextViewNavViewLabelTo1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    NSInteger showTextViewNavViewNumberTo1 = arc4random_uniform(20);
    NSLog(@"：%ld", (long)showTextViewNavViewNumberTo1);
    showTextViewNavViewLabelTo1.text = [NSString stringWithFormat:@"%ld",(long)showTextViewNavViewNumberTo1];
    [showTextViewNavViewLabelTo1 addSubview:showTextViewNavViewLabelTo1];
    
    UIImageView * showTextViewNavViewLabelTo2 = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    [showTextViewNavViewViewTo1 addSubview:showTextViewNavViewLabelTo2];
    
}
- (void)showOldAddNavViewToMainOldView1{
    UIView * oldBgSS = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    oldBgSS.clipsToBounds = YES;
       UILabel * oldshowSSSSTip = [[UILabel alloc]init];
    oldshowSSSSTip.clipsToBounds = YES;
    oldshowSSSSTip.text = @"kass显示区";
    oldshowSSSSTip.textColor = ColorHex(@"#f0f0f0");
    oldshowSSSSTip.textAlignment = NSTextAlignmentCenter;
    oldshowSSSSTip.font = [UIFont systemFontOfSize:28];
    oldshowSSSSTip.hidden = YES;
    [self.view addSubview:oldshowSSSSTip];
    [self.view addSubview:oldBgSS];
    
    UIButton * sendBtn = [[UIButton alloc]initWithFrame:CGRectMake(KScreen_W-75, kStatusBarHeight+10, 60, 46)];
    sendBtn.layer.cornerRadius = 3;
    sendBtn.backgroundColor = [UIColor whiteColor];
    [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    [sendBtn setTitleColor:ColorHex(@"#333333") forState:UIControlStateNormal];
    sendBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [sendBtn addTarget:self action:@selector(sendTap) forControlEvents:UIControlEventTouchUpInside];
    [oldBgSS addSubview:sendBtn];
    
    UIView * sendBg = [[UIView alloc]initWithFrame:CGRectMake(15, kStatusBarHeight+66, KScreen_W-30, (KScreen_H-KSafeAreaBottomHeight-25-(kStatusBarHeight+66))/2)];
    sendBg.backgroundColor = [UIColor whiteColor];
    sendBg.layer.cornerRadius = 3;
    [oldBgSS addSubview:sendBg];
    
    UILabel * sendTip = [[UILabel alloc]initWithFrame:CGRectMake(0, (sendBg.frame.size.height-40)/2, sendBg.frame.size.width, 40)];
    sendTip.text = @"发送区";
    sendTip.textColor = ColorHex(@"#f0f0f0");
    sendTip.textAlignment = NSTextAlignmentCenter;
    sendTip.font = [UIFont systemFontOfSize:28];
    [sendBg addSubview:sendTip];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onSingleTap:)];
    [self.view addGestureRecognizer:singleTap];
    
    KStrongSelf
    CGFloat lineWidth = (1. / [UIScreen mainScreen].scale);
    //contentView
    _contentView = [[UIView alloc] init];
    _contentView.backgroundColor = [UIColor whiteColor];
       UILabel * oldshowSSSSTip = [[UILabel alloc]init];
    oldshowSSSSTip.clipsToBounds = YES;
    oldshowSSSSTip.text = @"kass显示区";
    oldshowSSSSTip.textColor = ColorHex(@"#f0f0f0");
    oldshowSSSSTip.textAlignment = NSTextAlignmentCenter;
    oldshowSSSSTip.font = [UIFont systemFontOfSize:28];
    oldshowSSSSTip.hidden = YES;
    [self.view addSubview:oldshowSSSSTip];
    [self.view addSubview:_contentView];
    //topLineView1
    _topLineView1 = [[UIView alloc] init];
    //titleLabel
    _titleLabel = [[UILabel alloc] init];
    _titleLabel.text = @"自定义评价界面";
    _titleLabel.font = [UIFont systemFontOfSize:15];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    [_contentView addSubview:_titleLabel];
    //closeButton
    _closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_closeButton setImage:[self getImageInBundle:@"icon_evaluation_close"] forState:UIControlStateNormal];
    [_closeButton addTarget:self action:@selector(onClose:) forControlEvents:UIControlEventTouchUpInside];
    [_contentView addSubview:_closeButton];
    //topLineView2
    _topLineView2 = [[UIView alloc] init];
    //scrollView
    _scrollView = [[UIScrollView alloc] init];
    [_contentView addSubview:_scrollView];
    //satisButtons & tagViews
   
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    CGFloat lineWidth = (1. / [UIScreen mainScreen].scale);
    //contentView
    BOOL isLandscape = UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation);
    if (!CGRectEqualToRect(_kbFrame, CGRectZero) && _kbFrame.origin.y < CGRectGetHeight(self.view.bounds) && CGRectGetHeight(_kbFrame)) {
        CGRect contentFrame = _contentView.frame;
        contentFrame.origin.y = _kbFrame.origin.y - contentFrame.size.height;
        _contentView.frame = contentFrame;
    }
}

#pragma mark - action
- (void)onSelect:(id)sender {
    [self.view endEditing:YES];
    //clean
    _selectedButton.selected = NO;
    _selectedButton.titleLabel.backgroundColor = [UIColor clearColor];
    _selectedTagView.hidden = YES;
    //selectedButton
    UIButton *button = (UIButton *)sender;
    _selectedButton = button;
    _selectedButton.selected = YES;
    //selectedButton animation
    CGAffineTransform oldTransForm =  button.imageView.transform;
    CGAffineTransform transform = CGAffineTransformScale(oldTransForm, 1.2, 1.2);
    [UIView animateWithDuration:0.1 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        button.imageView.transform = transform;
    } completion:^(BOOL finished){
        [UIView animateWithDuration:0.1 delay:0.05 options:UIViewAnimationOptionCurveLinear animations:^{
            button.imageView.transform = oldTransForm;
        } completion:nil];
    }];
    //selectedTagView
    for (UIView *tagView in _tagViews) {
        if (tagView.tag == button.tag) {
            _selectedTagView = tagView;
        }
    }
    _selectedTagView.hidden = NO;
    [_contentView bringSubviewToFront:_selectedTagView];
    
   
    //submiteButton
    [self updateSubmitButtonEnable:QYEvaluationSubmitTypeEnable];
    
    [self.view setNeedsLayout];
}

- (void)onSubmit:(id)sender {
    
}

- (NSArray *)getSelectedTags {

    NSMutableArray *selectedTags = [NSMutableArray array];
    for (UIButton *tagButton in _selectedTagView.subviews) {
        if (tagButton.selected) {
            if (tagButton.titleLabel.text) {
                [selectedTags addObject:tagButton.titleLabel.text];
            }
        }
    }
    return selectedTags;
}

- (void)updateSubmitButtonEnable:(QYEvaluationSubmitType)type {
    if (type == QYEvaluationSubmitTypeEnable) {
        self.view.userInteractionEnabled = YES;
        _submitButton.enabled = YES;
        [_submitButton setTitle:@"提 交" forState:UIControlStateNormal];
    } else if (type == QYEvaluationSubmitTypeUnable) {
        self.view.userInteractionEnabled = YES;
        _submitButton.enabled = NO;
        [_submitButton setTitle:@"提 交" forState:UIControlStateNormal];
    } else if (type == QYEvaluationSubmitTypeSubmitting) {
        self.view.userInteractionEnabled = NO;
        _submitButton.enabled = NO;
        [_submitButton setTitle:@"提交中..." forState:UIControlStateNormal];
    }
}

#pragma mark - close
- (void)onClose:(id)sender {
    if (_submitButton.enabled) {
        //解决iOS键盘消失动画被打断后闪一下问题
        KStrongSelf
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSString *title = @"是否放弃当前评价";
            UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:title
                                                             message:@""
                                                            delegate:strongSelf
                                                   cancelButtonTitle:nil
                                                   otherButtonTitles:nil, nil];
            [dialog addButtonWithTitle:@"取消"];
            [dialog addButtonWithTitle:@"确定"];
            [dialog show];
        });
    } else {
        [self closeViewController];
    }
    [self.textView resignFirstResponder];   //否则close评价窗口键盘会抖动
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        [self.textView becomeFirstResponder];
    } else if (buttonIndex == 1) {
        [self closeViewController];
    }
}

- (void)closeViewController {
    [self dismissViewControllerAnimated:YES completion:^{ }];
}

#pragma mark - gesture
-(void)onSingleTap:(UITapGestureRecognizer *)recognizer {
    [self.view endEditing:YES];
}

#pragma mark - UITextViewDelegate
- (void)textViewDidBeginEditing:(UITextView *)textView {
//    [_scrollView ysf_scrollToBottom:YES];
}

- (void)textViewDidChange:(UITextView *)textView {
    if (textView.text.length > 0) {
        _placeholderLabel.hidden = YES;
    } else {
        _placeholderLabel.hidden = NO;
    }
    
    //解决自动上下移动问题
    CGRect line = [textView caretRectForPosition:textView.selectedTextRange.start];
    CGFloat overflow = line.origin.y + line.size.height - (textView.contentOffset.y + textView.bounds.size.height - textView.contentInset.bottom - textView.contentInset.top);
    if (overflow > 0) {
        // We are at the bottom of the visible text and introduced a line feed, scroll down (iOS 7 does not do it)
        // Scroll caret to visible area
        CGPoint offset = textView.contentOffset;
        offset.y += overflow + 7; // leave 7 pixels margin
        // Cannot animate with setContentOffset:animated: or caret will not appear
        [textView setContentOffset:offset];
    }
    
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@""]) {
        return YES;
    }
    if (range.location >= 100) {
        return NO;
    } else {
        return YES;
    }
}

#pragma mark - QYEvaluationResolveViewDelegate

#pragma mark - other
- (void)showToast:(NSString *)toast {
    if (toast.length) {
    }
}

- (void)updateLastResult {

        [self updateSubmitButtonEnable:QYEvaluationSubmitTypeUnable];
    
}


- (UIImage *)getImageInBundle:(NSString *)imageName {
    NSString *name = [@"QYCustomResource.bundle" stringByAppendingPathComponent:imageName];
    UIImage *image = [UIImage imageNamed:name];
    if (!image) {
        name = [@"QYResource.bundle" stringByAppendingPathComponent:imageName];
        image = [UIImage imageNamed:name];
    }
    return image;
}


@end
